package mspbots.tsheets.common;

import org.springframework.util.LinkedMultiValueMap;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * mspbots.smileback.QueryParams
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/10/26
 */
public class QueryParams extends LinkedMultiValueMap<String, String> {

    private int perPage;

    private int page;

    private ZonedDateTime modifiedSince;

    public QueryParams() {
        super(new LinkedHashMap<>());
        this.perPage = 50;
        this.page = 1;
        this.put("per_page", List.of(String.valueOf(this.perPage)));
        this.put("page", List.of("1"));
    }

    /**
     * Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}
     * with the given initial capacity.
     *
     * @param initialCapacity the initial capacity
     */
    public QueryParams(int initialCapacity) {
        super(new LinkedHashMap<>(initialCapacity));
    }

    /**
     * Copy constructor: Create a new LinkedMultiValueMap with the same mappings as
     * the specified Map. Note that this will be a shallow copy; its value-holding
     * List entries will get reused and therefore cannot get modified independently.
     *
     * @param otherMap the Map whose mappings are to be placed in this Map
     * @see #clone()
     * @see #deepCopy()
     */
    public QueryParams(Map<String, List<String>> otherMap) {
        super(new LinkedHashMap<>(otherMap));
    }

    /**
     * default query params
     * max records 500
     * page 0
     *
     * @return default query body
     */
    public static QueryParams withDefault() {
        QueryParams queryParams = new QueryParams(8);
        return queryParams.setPerPage(50).setPage(1)
                .setModifiedSince(ZonedDateTime.of(2000, 1, 1,
                0, 0, 0, 0, ZoneId.systemDefault()));
    }


    public QueryParams setPerPage(Integer perPage) {
        this.put("per_page", List.of(perPage.toString()));
        this.perPage = perPage;
        return this;
    }

    public QueryParams setPage(Integer page) {
        this.put("page", List.of(page.toString()));
        this.page = page;
        return this;
    }

    public int getPage() {
        return page;
    }

    public QueryParams setModifiedSince(ZonedDateTime zonedDateTime) {
        this.put("modified_since", List.of(zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX"))));
        this.modifiedSince = zonedDateTime;
        return this;
    }
}
